﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SKYPE4COMLib;
using Skyper.Shared;

namespace Skyper.Service {
	public class SkypeHost {
		#region Fields
		private readonly ISkype skype;
		#endregion
		#region Constructor
		public SkypeHost() {
			this.skype = CreateSkype();
		}
		#endregion
		#region Private
		private ISkype CreateSkype() {
			ISkype skype = new SKYPE4COMLib.Skype();

			_ISkypeEvents_Event events = (_ISkypeEvents_Event)skype;

			events.Error += new _ISkypeEvents_ErrorEventHandler(Skype_Error);
			events.Reply += new _ISkypeEvents_ReplyEventHandler(Skype_Reply);
			events.Command += new _ISkypeEvents_CommandEventHandler(Skype_Command);
			return skype;
		}

		private void Skype_Command(Command pCommand) {
			
		}
		private void Skype_Reply(Command pCommand) {
			
		}
		private void Skype_Error(Command pCommand, int Number, string Description) {
			
		}

		private ContactModel Convert(IUser usr) {
			ContactModel model = new ContactModel();

			model.Birthday = usr.Birthday;
			model.City = usr.City;
			model.Country = usr.Country;
			model.Displayname = usr.DisplayName;
			model.Fullname = usr.FullName;
			model.Mood = usr.MoodText;
			model.Username = usr.Handle;

			return model;
		}
		private ChatModel Convert(IChat chat) {
			ChatModel model = new ChatModel();

			model.Created = chat.Timestamp;
			model.Updated = chat.ActivityTimestamp;

			model.Partner = chat.DialogPartner;

			return model;
		}
		private MessageModel Convert(IChatMessage message) {
			MessageModel model = new MessageModel();

			model.Text = message.Body;
			model.ID = message.Id;
			model.Time = message.Timestamp;
			model.Username = message.FromHandle;

			return model;
		}
		private MessageModel[] Convert(IChatMessageCollection data) {
			List<MessageModel> list = new List<MessageModel>();

			for (int i = 0; i < data.Count; i++) {
				var msg = Convert(data[i]);

				if (msg != null) {
					list.Add(msg);
				}
			}

			return list.ToArray();
		}
		#endregion
		#region Public
		public ContactModel[] GetContacts() {
			List<ContactModel> list = new List<ContactModel>();

			foreach (IGroup grp in this.skype.Groups) {
				foreach (IUser usr in grp.Users) {
					if (!ContactModel.Contains(list, usr.Handle)) {
						ContactModel mod = Convert(usr);
						
						list.Add(mod);
					}
				}
			}
			return list.ToArray();
		}
		public ChatModel[] GetChats() {
			List<ChatModel> list = new List<ChatModel>();



			return list.ToArray();
		}
		public MessageModel[] GetMessages(String username) {
			//Look in recent chats
			foreach (IChat chat in this.skype.RecentChats) {
				if (chat.DialogPartner == username) {
					IChatMessageCollection coll = chat.RecentMessages;

					return Convert(coll);
				}
			}

			return null;
		}
		#endregion
	}
}
